package org.beetl.json.node;

import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Method;
import java.util.List;

import org.beetl.json.AbstractOutputNode;
import org.beetl.json.JsonTool;
import org.beetl.json.Location;
import org.beetl.json.Policy;
import org.beetl.json.util.JsonUtil;
import org.beetl.json.util.MethodInvoker;

public class ListAttributeNode extends AbstractOutputNode {


	private String attrName;
	Class attrType = null;
	MethodInvoker methodProxy = null;
	public ListAttributeNode(Method m){
		
		this.attrType =List.class;
		this.attrName = JsonUtil.getAttribute(m);
		methodProxy = new MethodInvoker(m);
	
	}
	@Override
	public  void render(Object obj,Writer w,String after) throws IOException{
		
		String key = attrName;
		String value= null;
		
		if(this.keyAction!=null){
			
			Object keyValue = keyAction.doit(obj, this);
			if(keyValue==null) return ;
			key = keyValue.toString();
		}
		w.write(key);
		w.write(":");
		Object attrValue = methodProxy.invoke(obj);
		List list = (List)attrValue;
		if(this.valueAction!=null){
			list = (List)valueAction.doit(attrValue, this);	
		}
		w.write("[");
		for(int i=0;i<list.size();i++)
		for(Object item :list){
			Policy policy = JsonTool.getDefaultPolicy(item.getClass());
			policy.toJson(w, item);
			w.write(",");
		}
		w.write("]");
		
	

	}
	@Override
	protected boolean isMatch(Location location) {
		return location.match(this.attrType, this.attrName);
	}

}
